#!/usr/bin/python
#
# Copyright (C) 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


__author__ = 'e.bidelman (Eric Bidelman), r.yozzo (Ralph Yozzo)'

import logging
import cgi
import os
import gdata.auth
import gdata.docs
import gdata.docs.service
import gdata.spreadsheet
import gdata.spreadsheet.service
import gdata.alt.appengine

from google.appengine.api import urlfetch
from google.appengine.ext import db

from appengine_utilities.sessions import Session
from django.utils import simplejson
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

import gdata.spreadsheet.text_db
from xml.dom import minidom

SETTINGS = {
  'APP_NAME': 'brooklynmarathon-MyTracksFetcher-v1',
  'CONSUMER_KEY': 'runmatch.appspot.com',
  'CONSUMER_SECRET': 'jl0rSMtpxxKH88zYd2WBYWNB',
  'SIG_METHOD': gdata.auth.OAuthSignatureMethod.HMAC_SHA1,
  'SCOPES': ['http://docs.google.com/feeds/',
             'https://docs.google.com/feeds/',
  	     'https://spreadsheets.google.com/feeds/',
             'http://spreadsheets.google.com/feeds/'
	     ]
  }

gspreadsheet = gdata.spreadsheet.service.SpreadsheetsService(source=SETTINGS['APP_NAME'])
gspreadsheet.SetOAuthInputParameters(SETTINGS['SIG_METHOD'], SETTINGS['CONSUMER_KEY'],
                              consumer_secret=SETTINGS['CONSUMER_SECRET'])
gdata.alt.appengine.run_on_appengine(gspreadsheet)

gdocs = gdata.docs.service.DocsService(source=SETTINGS['APP_NAME'])
gdocs.SetOAuthInputParameters(SETTINGS['SIG_METHOD'], SETTINGS['CONSUMER_KEY'],
                              consumer_secret=SETTINGS['CONSUMER_SECRET'])
gdata.alt.appengine.run_on_appengine(gdocs)

client = gdata.spreadsheet.text_db.DatabaseClient()
client._GetDocsClient().SetOAuthInputParameters(SETTINGS['SIG_METHOD'], SETTINGS['CONSUMER_KEY'],
                              consumer_secret=SETTINGS['CONSUMER_SECRET'])
client._GetSpreadsheetsClient().SetOAuthInputParameters(SETTINGS['SIG_METHOD'], SETTINGS['CONSUMER_KEY'],
                              consumer_secret=SETTINGS['CONSUMER_SECRET'])
logging.getLogger().setLevel(logging.DEBUG)

def checkvalue(variable):
  if variable is None:
      return ''
  else:
      return str(variable)

def process_db2xml(domexport, dom, title, user):
    if not users.get_current_user():
      self.redirect(users.create_login_url(self.request.uri))


    for node in dom.getElementsByTagName('entry'):  # visit every node <bar />
#      logging.debug('node.toxml(): %s' % node.toxml())
      logging.debug('process_db2xml: title: %s' % node.getElementsByTagName('title')[0].firstChild.data)
#      logging.debug('content: %s' % node.getElementsByTagName('content')[0].firstChild.data)
#      logging.debug('date: %s' % node.getElementsByTagName('gsx:date')[0].firstChild.data)
#      logging.debug('distance: %s' % node.getElementsByTagName('gsx:distance')[0].firstChild.data)
#      logging.debug('distanceunit: %s' % node.getElementsByTagName('gsx:distanceunit')[0].firstChild.data)
#      logging.debug('movingtime: %s' % node.getElementsByTagName('gsx:movingtime')[0].firstChild.data)
#      logging.debug('map: %s type: %s' % (node.getElementsByTagName('gsx:map')[0].firstChild.data, title))

      nodeexport = domexport.createElement("result")  # creates <foo />
      try:
        nodeexport.setAttribute('racename', node.getElementsByTagName('title')[0].firstChild.data)
	workdate = node.getElementsByTagName('gsx:date')[0].firstChild.data
	dow, month, day, time, timezone, year = workdate.split(' ')
	month = month.replace('Jan', '01')
	month = month.replace('Feb', '02')
	month = month.replace('Mar', '03')
	month = month.replace('Apr', '04')
	month = month.replace('May', '05')
	month = month.replace('Jun', '06')
	month = month.replace('Jul', '07')
	month = month.replace('Aug', '08')
	month = month.replace('Sep', '09')
	month = month.replace('Oct', '10')
	month = month.replace('Nov', '11')
	month = month.replace('Dec', '12')

	nodeexport.setAttribute('racedate', '%s-%s-%s' % (year, month, day))
	nodeexport.setAttribute('date', '%s-%s-%s' % (year, month, day))
	nodeexport.setAttribute('created', '%s-%s-%s' % (year, month, day))
	nodeexport.setAttribute('modified', '%s-%s-%s' % (year, month, day))

#	nodeexport.setAttribute('racedate', node.getElementsByTagName('gsx:date')[0].firstChild.data)
#	nodeexport.setAttribute('date', node.getElementsByTagName('gsx:date')[0].firstChild.data)
#	nodeexport.setAttribute('created', node.getElementsByTagName('gsx:date')[0].firstChild.data)
#	nodeexport.setAttribute('modified', node.getElementsByTagName('gsx:date')[0].firstChild.data)
	nodeexport.setAttribute('distanceInMiles', node.getElementsByTagName('gsx:distance')[0].firstChild.data)
	nodeexport.setAttribute('distance_in_miles', node.getElementsByTagName('gsx:distance')[0].firstChild.data)
	nodeexport.setAttribute('comments', 'map: %s type: %s' % (node.getElementsByTagName('gsx:map')[0].firstChild.data, title))
		## 'map: %s' % node.getElementsByTagName('gsx:map')[0].firstChild.data)
	nodeexport.setAttribute('guntime', node.getElementsByTagName('gsx:movingtime')[0].firstChild.data)
	nodeexport.setAttribute('nettime', node.getElementsByTagName('gsx:movingtime')[0].firstChild.data)


        age = 0
	if user.age:
	  age = user.age
	if node.getElementsByTagName('gsx:age') and node.getElementsByTagName('gsx:age')[0].firstChild:
          age = node.getElementsByTagName('gsx:age')[0].firstChild.data
	nodeexport.setAttribute('age', checkvalue(age))
	# nodeexport.setAttribute('age', checkvalue('46'))

	nodeexport.setAttribute('agegradedpercent', checkvalue(''))
	nodeexport.setAttribute('ageplace', checkvalue(''))
	nodeexport.setAttribute('datasource', checkvalue('runmatch.appspot.com:%s:%s' % (title,users.get_current_user())))
	first = 'first'
#        first = request.get('first', default_value='first')
#        last = request.get('last', default_value='last')
#        age = request.get('age', default_value='10')
#        team = request.get('team', default_value='')
	if user.first:
	  first = user.first
	if node.getElementsByTagName('gsx:first') and node.getElementsByTagName('gsx:first')[0].firstChild:
          first = node.getElementsByTagName('gsx:first')[0].firstChild.data
	nodeexport.setAttribute('first', checkvalue(first))

	nodeexport.setAttribute('gender', checkvalue('M'))
	nodeexport.setAttribute('genderplace', checkvalue(''))
	nodeexport.setAttribute('ip', checkvalue(''))

        last = 'last'
	if user.last:
	  last = user.last
	if node.getElementsByTagName('gsx:last') and node.getElementsByTagName('gsx:last')[0].firstChild:
          last = node.getElementsByTagName('gsx:last')[0].firstChild.data
	nodeexport.setAttribute('last', checkvalue(last))
	# nodeexport.setAttribute('last', checkvalue('Yozzo'))

	nodeexport.setAttribute('overallplace', checkvalue(''))
	nodeexport.setAttribute('pace', checkvalue(''))
	nodeexport.setAttribute('racedirector', checkvalue(users.get_current_user()))

        team = ''
	if user.team:
	  team = user.team
	if node.getElementsByTagName('gsx:team') and node.getElementsByTagName('gsx:team')[0].firstChild:
          team = node.getElementsByTagName('gsx:team')[0].firstChild.data
	nodeexport.setAttribute('team', checkvalue(team))
	# nodeexport.setAttribute('team', checkvalue('WSX'))

	nodeexport.setAttribute('training', checkvalue('True'))

        #nodeexport.setAttribute('age', checkvalue(node.getElementsByTagName('age')[0].firstChild.data))
      except Exception, e:
        logging.error('process_db2xml Unexpected error: %s', e)
	

#      node.setAttribute('age', str(result.age))
#      node.setAttribute('agegradedpercent', checkvalue(result.agegradedpercent))
#      node.setAttribute('ageplace', checkvalue(result.ageplace))
#      node.setAttribute('comments', str(result.comments.strip()))
#      node.setAttribute('created', str(result.created))
#      node.setAttribute('datasource', result.datasource)
#      node.setAttribute('date', result.date)
#      node.setAttribute('distanceInMiles', str(result.distanceInMiles))
#      node.setAttribute('distance_in_miles', str(result.distance_in_miles))
#      node.setAttribute('first', result.first)
#      node.setAttribute('gender', result.gender)
#
#      #node.setAttribute('genderplace', str(result.genderplace))
#      node.setAttribute('genderplace', checkvalue(result.genderplace))
#
#      node.setAttribute('guntime', result.guntime.strip())
#      node.setAttribute('ip', result.ip)
#      node.setAttribute('last', result.last)
#      node.setAttribute('modified', str(result.modified))
#      node.setAttribute('nettime', result.nettime.strip())
#
#      node.setAttribute('overallplace', checkvalue(result.overallplace))
#      node.setAttribute('pace', checkvalue(result.pace))
#
#
#      node.setAttribute('racedate', str(result.racedate))
##      node.setAttribute('racedirector', result.racedirector)
#      node.setAttribute('racename', result.racename)
#      node.setAttribute('team', checkvalue(result.team))
#      node.setAttribute('training', str(result.training))
#      #node.setAttribute('training', 'XXX')
      domexport.childNodes[0].appendChild(nodeexport)  # appends at end of 1st child's children
    return domexport

class User(db.Model):
  first = db.StringProperty(required=True,default='first name')
  last = db.StringProperty(required=True,default='last name')
  age = db.IntegerProperty(required=True,default=20,choices=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99])
  team = db.StringProperty(required=False)
  owner = db.UserProperty()

class MainPage(webapp.RequestHandler):
  """Main page displayed to user."""

  # GET /
  def get(self):
    logging.debug('current_user: %s' % users.get_current_user())
    if not users.get_current_user():
      logging.debug('redirect: %s' % users.create_login_url(self.request.uri))
      self.redirect(users.create_login_url(self.request.uri))

    access_token = gdocs.token_store.find_token('%20'.join(SETTINGS['SCOPES']))
    logging.debug('access_token: %s' % access_token)
    if isinstance(access_token, gdata.auth.OAuthToken):
      form_action = '/fetch_data'
      form_value = 'Synchronize MyTracks to run.wsxnyc.org'
      revoke_token_link = True
    else:
      form_action = '/get_oauth_token'
      form_value = 'Give this website access to my Google Docs'
      revoke_token_link = None

    user = User()
    q = db.GqlQuery('SELECT * FROM User WHERE owner = :1 LIMIT 1', users.get_current_user())
    if q: 
      results = q.fetch(1)
      for result in results:
        user.age=result.age
        user.first=result.first
        user.last=result.last
        user.team=result.team
  
    template_values = {
      'form_action': form_action,
      'form_value': form_value,
      'user': users.get_current_user(),
      'save_user': user,
      'revoke_token_link': revoke_token_link,
      'oauth_token': access_token,
      'consumer': gdocs.GetOAuthInputParameters().GetConsumer(),
      'sig_method': gdocs.GetOAuthInputParameters().GetSignatureMethod().get_name()
      }

    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, template_values))


class OAuthDance(webapp.RequestHandler):
  """Handler for the 3 legged OAuth dance, v1.0a."""

  """This handler is responsible for fetching an initial OAuth request token,
  redirecting the user to the approval page.  When the user grants access, they
  will be redirected back to this GET handler and their authorized request token
  will be exchanged for a long-lived access token."""

  # GET /get_oauth_token
  def get(self):
    """Invoked after we're redirected back from the approval page."""

    logging.debug('QQQ: GET get_oauth_token')
    self.session = Session()
    oauth_token = gdata.auth.OAuthTokenFromUrl(self.request.uri)
    logging.debug('QQQ: oauth_token: %s' % oauth_token)
    if oauth_token:
      oauth_token.secret = self.session['oauth_token_secret']
      oauth_token.oauth_input_params = gdocs.GetOAuthInputParameters()
      gdocs.SetOAuthToken(oauth_token)
      logging.debug('setoauthtoken1')
      client._GetDocsClient().SetOAuthToken(oauth_token)
      client._GetSpreadsheetsClient().SetOAuthToken(oauth_token)

      # 3.) Exchange the authorized request token for an access token
      oauth_verifier = self.request.get('oauth_verifier', default_value='')
      access_token = gdocs.UpgradeToOAuthAccessToken(
          oauth_verifier=oauth_verifier)

      # Remember the access token in the current user's token store
      if access_token and users.get_current_user():
        gdocs.token_store.add_token(access_token)
      elif access_token:
        gdocs.current_token = access_token
        gdocs.SetOAuthToken(access_token)
        logging.debug('setoauthtoken2')
        client._GetDocsClient().SetOAuthToken(oauth_token)
        client._GetSpreadsheetsClient().SetOAuthToken(oauth_token)

    self.redirect('/')

  # POST /get_oauth_token
  def post(self):
    """Fetches a request token and redirects the user to the approval page."""

    self.session = Session()
    
    if users.get_current_user():
      # 1.) REQUEST TOKEN STEP. Provide the data scope(s) and the page we'll
      # be redirected back to after the user grants access on the approval page.
      req_token = gdocs.FetchOAuthRequestToken(
          scopes=SETTINGS['SCOPES'], oauth_callback=self.request.uri)

      # When using HMAC, persist the token secret in order to re-create an
      # OAuthToken object coming back from the approval page.
      self.session['oauth_token_secret'] = req_token.secret

      # Generate the URL to redirect the user to.  Add the hd paramter for a
      # better user experience.  Leaving it off will give the user the choice
      # of what account (Google vs. Google Apps) to login with.
      domain = self.request.get('domain', default_value='default')
      approval_page_url = gdocs.GenerateOAuthAuthorizationURL(
          extra_params={'hd': domain})

      # 2.) APPROVAL STEP.  Redirect to user to Google's OAuth approval page.
      self.redirect(approval_page_url)

class FetchDataSpreadsheet(OAuthDance):
  # GET /fetch_data
  def get(self):
    try:
      #print 'get db...' 
      self.response.out.write('get db...<br/>')
      db = client.GetDatabases(name='My Tracks-street running')
      table=db[0].GetTables()[0]
      rows=table.GetRecords(1,1000)
      for row in rows:
        #print row.content.get('name') 
        self.response.out.write( '%s<br/>' % row.content.get('name') )
        #self.response.out.write('%s<br/>' % row.content.get('name') )
      self.response.out.write('get db done<br/>')
    except gdata.service.RequestError, error:
      self.response.out.write('error %s' % error)
      OAuthDance.post(self)

class TestAuthSub():
  # GET /fetch_data
  def get(self):
    client = gdata.spreadsheet.text_db.DatabaseClient()
    auth_url = client._GetDocsClient().GenerateAuthSubURL(next='/testauthsub2',
    	  scope='http://spreadsheets.google.com/feeds/ http://docs.google.com/feeds/documents/')

class TestAuthSub2():
  # GET /fetch_data
  def get(self):
    client._GetDocsClient().SetAuthSubToken(token)
    client._GetDocsClient().UpgradeToSessionToken()
    client._GetSpreadsheetsClient().SetAuthSubToken(client._GetDocsClient().GetAuthSubToken())
    
    db = client.CreateDatabase('google_spreadsheets_db auth sub test')

class FetchData(OAuthDance):
  """Fetches the user's data."""

  """This class inherits from OAuthDance in order to utilize OAuthDance.post()
  in case of a request error (e.g. the user has a bad token)."""


  # GET /fetch_data
  def get(self):
    self.redirect('/')

  # POST /fetch_data
  def post(self):
    """Fetches the user's data."""

#      try:
#        # logging.debug('XXX...')
#        # db_entry = gdocs.Get( 'http://spreadsheets.google.com/feeds/list/rPO6RTygq1__cvSnOquYPvQ/od6/private/full')
#        # logging.debug('db_entry %s' % db_entry)
#        # GET /feeds/list/rPO6RTygq1__cvSnOquYPvQ/od6/private/full?oauth_version=1.0&oauth_nonce=b698831504af9ed3a090471de8e174ce&oauth_timestamp=1248829065&oauth_consumer_key=runmatch.appspot.com&oauth_token=1%2FKyQe_v18MngeKbpmbWVDSGATiaQZnWPB51nTvo8n9Sw&oauth_signature_method=HMAC-SHA1&oauth_signature=Y4jHlD0s9IIQJSvWVO52oHD0I6I%3D
#        url = 'http://spreadsheets.google.com/feeds/list/rPO6RTygq1__cvSnOquYPvQ/od6/private/full?oauth_version=1.0&oauth_nonce=14c88d18024c6be61d4a70a9f52caca2&oauth_timestamp=1252165079&oauth_consumer_key=runmatch.appspot.com&oauth_token=1%2F1P4obi5sEyWv_SY3S_cYHw&oauth_signature_method=HMAC-SHA1&oauth_signature=3%2Fze68mlN4t2L5RYHVgLvvZWJdE%3D'
#        # url = 'http://spreadsheets.google.com/feeds/list/rPO6RTygq1__cvSnOquYPvQ/od6/private/full?oauth_version=1.0&oauth_nonce=8faa0bf3c85426b9868e4efce2ffb65d&oauth_timestamp=1252110992&oauth_consumer_key=runmatch.appspot.com&oauth_token=1%2FnEnFOsatIvWvnvRnwwctaA&oauth_signature_method=HMAC-SHA1&oauth_signature=m7FrfsrGhJZXrgsS23pymhpwCdM%3D'
#        #                                                                                         oauth_version=1.0&oauth_nonce=2e3d7c388a1b9274d7aad384f5d6da23&oauth_timestamp=1248564262&oauth_consumer_key=runmatch.appspot.com&oauth_token=1%2FCP_7C4adnF465eM4gYTHcGATiaQZnWPB51nTvo8n9Sw&oauth_signature_method=HMAC-SHA1&oauth_signature=2UNU%2FxM0JU0CuUzpu9fkP2PYLeE%3D'
#        # url = 'http://spreadsheets.google.com/feeds/list/rPO6RTygq1__cvSnOquYPvQ/od6/private/full?oauth_version=1.0&oauth_nonce=2e3d7c388a1b9274d7aad384f5d6da23&oauth_timestamp=1248564262&oauth_consumer_key=runmatch.appspot.com&oauth_token=1%2FCP_7C4adnF465eM4gYTHcGATiaQZnWPB51nTvo8n9Sw&oauth_signature_method=HMAC-SHA1&oauth_signature=2UNU%2FxM0JU0CuUzpu9fkP2PYLeE%3D'
#        # url = 'http://spreadsheets.google.com/feeds/list/rPO6RTygq1__cvSnOquYPvQ/od6/private/full?oauth_version=1.0&oauth_nonce=15afb0e3b30d4adebca490e20ddfc924&oauth_timestamp=1248547638&oauth_consumer_key=runmatch.appspot.com&start-index=1&max-results=1000&oauth_token=1%2FVOhFwJAPWkMVErjhMKvjOWATiaQZnWPB51nTvo8n9Sw&oauth_signature_method=HMAC-SHA1&oauth_signature=jflMfd6Old4d3tajU7pHJIDbjEU%3D'
#        logging.debug('result: url: %s' % url)
#        result = urlfetch.fetch( url )
#        logging.debug('result:')
#        logging.debug(result)
#        logging.debug(result.content)
#      except:
#        logging.debug("GET SPREADSHEET: Unexpected error:")
#        # raise

#    first = self.request.get('first', default_value='first')
#    logging.debug("post: first: %s" % first)
#    last = self.request.get('last', default_value='last')
#    age = self.request.get('age', default_value='10')
#    team = self.request.get('team', default_value='')

    try:

      logging.debug('GETDOCFEED before...')
      feed = gdocs.GetDocumentListFeed()
      logging.debug('...after GETDOCFEED')

      json = []
      for entry in feed.entry:
        if entry.lastModifiedBy is not None:
          last_modified_by = entry.lastModifiedBy.email.text
        else:
          last_modified_by = ''
        if entry.lastViewed is not None:
          last_viewed = entry.lastViewed.text
        else:
          last_viewed = ''

        # if entry.title.text == 'My Tracks-street running':
          # db_entry = gdocs.Get( 'http://spreadsheets.google.com/feeds/list/' + entry.resourceId.text + '/od6/private/full')
	if entry.title.text == 'My Tracks-street running' or entry.title.text == 'My Tracks-trail running' or entry.title.text == 'My Tracks-road biking' or entry.title.text == 'My Tracks-walking' or entry.title.text == 'My Tracks':
	#if entry.title.text == 'Pennies for Peace Letter':
          db_entry = 'xxx'
          #db_entry = gdocs.GetDocumentListEntry( r'/feeds/documents/private/full/spreadsheet%3A' + entry.resourceId.text)
	  # db_entry = gdocs.Get( 'http://spreadsheets.google.com/feeds/list/' + entry.resourceId.text + '/od6/private/full')
	  # db_entry = gdocs.Get( 'http://spreadsheets.google.com/feeds/list/rPO6RTygq1__cvSnOquYPvQ/od6/private/full?oauth_version=1.0&oauth_nonce=15afb0e3b30d4adebca490e20ddfc924&oauth_timestamp=1248547638&oauth_consumer_key=runmatch.appspot.com&start-index=1&max-results=1000&oauth_token=1%2FVOhFwJAPWkMVErjhMKvjOWATiaQZnWPB51nTvo8n9Sw&oauth_signature_method=HMAC-SHA1&oauth_signature=jflMfd6Old4d3tajU7pHJIDbjEU%3D')
	  # GET&http%3A%2F%2Fspreadsheets.google.com%2Ffeeds%2Flist%2FrPO6RTygq1__cvSnOquYPvQ%2Fod6%2Fprivate%2Ffull&max-results%3D1000%26oauth_consumer_key%3Drunmatch.appspot.com%26oauth_nonce%3D15afb0e3b30d4adebca490e20ddfc924%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1248547638%26oauth_token%3D1%252FVOhFwJAPWkMVErjhMKvjOWATiaQZnWPB51nTvo8n9Sw%26oauth_version%3D1.0%26start-index%3D1

        else:
	  db_entry = 'yyy'

        json.append({'title': entry.title.text,
                     'links': {'alternate': entry.GetHtmlLink().href},
                     'published': entry.published.text,
                     'updated': entry.updated.text,
                     'resourceId': entry.resourceId.text,
                     'type': entry.GetDocumentType(),
                     'lastModifiedBy': last_modified_by,
                     'lastViewed': last_viewed
		     , 'db_entry': db_entry
                    })
	#if entry.title.text == 'My Tracks-street running':
	  #gdocs.DownloadSpreadsheet(entry.resourceId.text, 'xxx.csv')
	#self.response.out.write('key: %s <br/>' % entry.resourceId.text)

	## DEBUG HERE
	logging.debug('Title: text: %s' % entry.title.text)
        try:
          # if entry.title.text == 'My Tracks-street running' or entry.title.text == 'My Tracks-trail running':
	  if entry.title.text == 'My Tracks-running' or entry.title.text == 'My Tracks-street running' or entry.title.text == 'My Tracks-trail running' or entry.title.text == 'My Tracks-road biking' or entry.title.text == 'My Tracks-walking' or entry.title.text == 'My Tracks':
            logging.debug('before GETSPREADSHEETSFEED')
	    entrytype, entryresourceid = entry.resourceId.text.split(":")
            
            logging.debug('entryresourceid: %s' % entryresourceid)

            # data = gspreadsheet.GetListFeed(entry.resourceId.text)

            data = gspreadsheet.GetListFeed(entryresourceid)

            # uri = gspreadsheet.GetListFeed(entryresourceid)
            # data = urlfetch.fetch( uri )

            #data = gspreadsheet.GetSpreadsheetsFeed()
            logging.debug('...after GETSPREADSHEETSFEED')
            # logging.debug('data: %s' % data.content)
            logging.debug('data: %s' % data)
		
            try:
              dom = minidom.parseString(data)
            # dom = minidom.parseString(data.content)
            except Exception, e: 
              logging.error('DOM parseString error: %s', e)

            logging.debug('dom: %s' % dom)
#           logging.debug('dom: getElementsByTagName feed: %s' % dom.getElementsByTagName('feed'))
#           logging.debug('dom: getElementsByTagName entry: %s' % dom.getElementsByTagName('entry'))

            document = """<results></results>"""
            domexport = minidom.parseString(document)
            user = User()
            q = db.GqlQuery('SELECT * FROM User WHERE owner = :1 LIMIT 1', users.get_current_user())
            logging.debug('q: %s' % q)
            if q: 
              results = q.fetch(1)
              logging.debug('len(results) %s' % len(results))
	      if results and len(results) > 0:
                # user = results.get(0)
                first = True
                for r in results:
                  if first:
                    user = r
	            first = False
	    if self.request.get('age'):
	      user.age = int(self.request.get('age'))
	    if self.request.get('first'):
	      user.first = self.request.get('first')
	    if self.request.get('last'):
	      user.last = self.request.get('last')
	    if self.request.get('team'):
	      user.team = self.request.get('team')
            user.owner = users.get_current_user()
	    user.put()
            
            xmlexport = process_db2xml(domexport, dom, entry.title.text, user)
            logging.debug('xmlexport: %s' % xmlexport.toxml())

            # urlmyrun = "http://wsxnyc.org/results-1.0-SNAPSHOT/results/results/buildpost.jsp?datasource=runmatch:%s" % user
	    # urlmyrun = 'http://wsxnyc.org/results-1.0-SNAPSHOT/results/results/buildpost.jsp?datasource=runmatch.appspot.com:fedex1@gmail.com:%s' % entry.title.text.replace(' ', '-')
	    urlmyrun = 'http://wsxnyc.org/results-1.0-SNAPSHOT/results/results/buildpost.jsp?datasource=runmatch.appspot.com:%s:%s:%s' % (entry.title.text.replace(' ', '-'), users.get_current_user(), user.age)
            logging.debug('urlmyrun: %s' % urlmyrun)
            resultmyrun = urlfetch.fetch(url=urlmyrun, payload=xmlexport.toxml(), method=urlfetch.POST, headers={'Content-Type': 'text/xml'})

#            for node in dom.getElementsByTagName('entry'):  # visit every node <bar />
#              logging.debug('node.toxml(): %s' % node.toxml())
#              logging.debug('title: %s' % node.getElementsByTagName('title')[0].firstChild.data)
#              logging.debug('content: %s' % node.getElementsByTagName('content')[0].firstChild.data)
#	      logging.debug('date: %s' % node.getElementsByTagName('gsx:date')[0].firstChild.data)
#	      logging.debug('distance: %s' % node.getElementsByTagName('gsx:distance')[0].firstChild.data)
#	      logging.debug('distanceunit: %s' % node.getElementsByTagName('gsx:distanceunit')[0].firstChild.data)
#	      logging.debug('movingtime: %s' % node.getElementsByTagName('gsx:movingtime')[0].firstChild.data)
#	      logging.debug('map: %s' % node.getElementsByTagName('gsx:map')[0].firstChild.data)

	      # logging.debug('gsx:date: %s' % node.getElementsByTagNameNS('gsx', 'date'))
#                logging.debug('distance: %s' % node.getElementsByTagName('distance')[0].firstChild.data)
#                logging.debug('averagemovingspeed: %s' % node.getElementsByTagName('averagemovingspeed')[0].firstChild.data)
#                logging.debug('map: %s' % node.getElementsByTagName('map')[0].firstChild.data)
#                logging.debug('updated: %s' % node.getElementsByTagName('updated')[0].firstChild.data)

#                for node1 in node.getElementsByTagName('title'):
#                  logging.debug('node1.toxml(): %s' % node1.toxml())
#                  logging.debug('node1.firstChild.data: %s' % node1.firstChild.data)

            # self.response.out.write('data: %s <br/>' % data)
        except Exception, e: 
          logging.error('SPREADSHEET Unexpected error: %s', e)
        

      # ListGetAction(gdocs, entry.resourceId.text, '1')

      self.response.out.write(simplejson.dumps(json))
    except gdata.service.RequestError, error:
      OAuthDance.post(self)


#    print 'get db...' 
#    db = client.GetDatabases(name='My Tracks-street running')
#    table=db[0].GetTables()[0]
#    rows=table.GetRecords(1,1000)
#    for row in rows:
#      print row.content.get('name') 
#      #self.response.out.write('%s<br/>' % row.content.get('name') )
#    print 'get db done.' 


#    q = gdata.docs.service.DocumentQuery()
#    q['title'] = 'My Tracks-street running'
#    q['title-exact'] = 'true'
#    feed = self.gd_client.Query(q.ToUri())
#    feed = gdocs.Query(q.ToUri())
#    PrintFeed(feed)

#  
#      """Prints out the contents of a feed to the console."""
#      #print '\n'
#      self.response.out.write('<br/>')
#      if not feed.entry:
#        #print 'No entries in feed.\n'
#        self.response.out.write('No entries in feed.<br/>')
#      for entry in feed.entry:
#        #print '%s %s %s' % (entry.title.text.encode('UTF-8'), entry.GetDocumentType(), entry.resourceId.text)
#        self.response.out.write('%s %s %s<br/>' % (entry.title.text.encode('UTF-8'), entry.GetDocumentType(), entry.resourceId.text))


class RevokeToken(webapp.RequestHandler):

  # GET /revoke_token
  def get(self):
    """Revokes the current user's OAuth access token."""

    try:
      gdocs.RevokeOAuthToken()
    except gdata.service.RevokingOAuthTokenFailed:
      pass

    gdocs.token_store.remove_all_tokens()
    self.redirect('/')



#  import gdata.spreadsheet.text_db
#  
#  class GetSpreadsheet(webapp.RequestHandler):
#    client = gdata.spreadsheet.text_db.DatabaseClient(username='fedex1@gmail.com',password='meromaro6')
#    db = client.GetDatabases(name='My Tracks-street running')
#    table=db[0].GetTables()[0]
#    rows=table.GetRecords(1,1000)
#    for row in rows:
#      print row.content.get('name'),',', row.content.get('date'),',',  row.content.get('movingtime'),',',  row.content.get('distance'),',',  row.content.get('distanceunit'),',', row.content.get('map')
#    
#    for row in rows:
#        print '==='
#        for cell in row.content:
#    	print '%s = %s' % (cell, row.content.get(cell), )
#          self.response.out.write('%s = %s' % (cell, row.content.get(cell), ))


#  def ListGetAction(gd_client, key, wksht_id):
#    # Get the list feed
#    feed = gd_client.GetListFeed(key, wksht_id)
#    PrintFeed(feed)
#    return feed
#  
#  def PrintFeed(feed):
#    for i, entry in enumerate(feed.entry):
#      if isinstance(feed, gdata.spreadsheet.SpreadsheetsCellsFeed):
#        print '%s %s\n' % (entry.title.text, entry.content.text)
#      elif isinstance(feed, gdata.spreadsheet.SpreadsheetsListFeed):
#        print '%s %s %s' % (i, entry.title.text, entry.content.text)
#        # Print this row's value for each column (the custom dictionary is
#        # built from the gsx: elements in the entry.) See the description of
#        # gsx elements in the protocol guide.
#        print 'Contents:'
#        for key in entry.custom:
#          print '  %s: %s' % (key, entry.custom[key].text)
#        print '\n',
#      else:
#        print '%s %s\n' % (i, entry.title.text)
  
def main():
  application = webapp.WSGIApplication([('/', MainPage),
                                        ('/get_oauth_token', OAuthDance),
                                        ('/fetch_data', FetchData),
                                        ('/fetch_data_spreadsheet', FetchDataSpreadsheet),
                                        #('/testauthsub', TestAuthSub),
                                        #('/testauthsub2', TestAuthSub2),
                                        ('/revoke_token', RevokeToken),
                                        #('/getdata', GetSpreadsheet)
					],
                                        debug=True)
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
